package com.mycompany.myapp.service;

import com.mycompany.myapp.domain.ElecBicycleUser;
import com.mycompany.myapp.domain.ElectricBicycle;
import com.mycompany.myapp.repository.ElecBicycleUserRepository;
import com.mycompany.myapp.repository.ElectricBicycleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by wys on 2018/7/24
 */

@Service
public class ElecBicycleUserService implements ElecBicycleUserServiceInterface {

    @Autowired
    ElectricBicycleService electricBicycleService;
    @Autowired
    ElecBicycleUserRepository elecBicycleUserRepository;
    @Autowired
    ElectricBicycleRepository electricBicycleRepository;

    Logger logger = LoggerFactory.getLogger(ElecBicycleUserService.class);

    /**
     * 借车成功，需要调用二维码接口 生成一个二维码
     * @param phoneNumber
     * @return
     */
    @Override
    public String borrowElecBicycle(String phoneNumber) {

        ElectricBicycle electricBicycle = electricBicycleService
            .getOneElectricBicycleUsed();

        logger.debug("------------electricBicycle:"+electricBicycle);

        ElecBicycleUser elecBicycleUser = elecBicycleUserRepository
            .findElecBicycleUserByPhoneNumber(phoneNumber);

        String state = "";

        if(electricBicycle != null) {
            if(elecBicycleUser.getOrder().equals("")) {
                elecBicycleUser.setOrder(electricBicycle.getElectricBicycleID());
                elecBicycleUserRepository.save(elecBicycleUser);
                electricBicycle.setUseState("false");
                electricBicycleRepository.save(electricBicycle);
                state = "borrow_success" + " 您的车号是:" + elecBicycleUser.getOrder();
            }else {
                state = "order_already";
            }
        }else if(electricBicycle == null) {
            state = "no_electricBicycle";
        }


        return state;
    }

    @Override
    public String returnElecBicycle(String phoneNumber) {

        ElecBicycleUser elecBicycleUser = elecBicycleUserRepository
            .findElecBicycleUserByPhoneNumber(phoneNumber);
        String state = "";

        if(!elecBicycleUser.getOrder().equals("")) {
            String bicycleID = elecBicycleUser.getOrder();

            ElectricBicycle electricBicycle = electricBicycleRepository
                .findElectricBicycleByElectricBicycleID(bicycleID);

            electricBicycle.setUseState("true");
            electricBicycleRepository.save(electricBicycle);
            elecBicycleUser.setOrder("");
            elecBicycleUserRepository.save(elecBicycleUser);

            state = "return_success";

        } else {
            state = "order_null_din't_borrow";
        }

        return state;
    }
}
